package impl

import (
	"context"

	"gitee.com/go-course/go9/projects/devcloud/mcenter/apps/permission"
	"gitee.com/go-course/go9/projects/devcloud/mcenter/apps/policy"
	"gitee.com/go-course/go9/projects/devcloud/mcenter/common/logger"
)

// 权限校验
func (i *impl) CheckPermission(ctx context.Context, in *permission.CheckPermissionRequest) (
	*permission.CheckPermissionResponse, error) {
	logger.L().Debug().Msgf("check permission request: %s", in)

	// 1. 查询出用户的策略
	policyQuery := policy.NewQueryPolicyRequest()
	policyQuery.UserId = in.UserId
	policyQuery.Namespace = in.Namespace
	policyQuery.WithRole = true
	ps, err := i.policy.QueryPolicy(ctx, policyQuery)
	if err != nil {
		return nil, err
	}

	checkResp := permission.NewCheckPermissionResponse()
	// 2. 根据该用户的角色, 判断权限
	roles := ps.GetRoles()
	for i := range roles {
		r := roles[i]
		if r.HasFeatrue(in.ServiceId, in.HttpMethod, in.HttpPath) {
			checkResp.HasPermisson = true
			checkResp.Role = r
			return checkResp, nil
		}
	}

	return checkResp, nil
}
